import "./index.css";
import { defineComponent, type PropType, ref, computed, watch } from "vue";
import FileUpload from "@/components/Upload/FileUpload.vue";
import { queryFileList } from "@/api/modules/fab";

const props = {
  modelValue: {
    type: Object as PropType<Array<string>>,
    default: () => []
  },
  moduleName: {
    type: String,
    default: "file"
  },
  disabled: {
    type: Boolean,
    default: false
  },
  fileAccept: {
    type: String,
    default: ".txt,.pdf,.doc,.docx,.xls,.xlsx"
  },
  limit: {
    type: Number,
    default: 3
  }
};

const emits = ["update:modelValue"];

export default defineComponent({
  name: "ReUploadFile",
  props,
  emits,
  setup(props, { emit, attrs }) {
    const loading = ref<boolean>(false);
    // 上传类型   add：新增  edit：编辑  view：查看
    const fileType = computed(() => (props.disabled ? "view" : "edit"));
    const fileList = ref<Array<any>>([]);
    const isImmediate = ref<boolean>(true);
    const changeFileListHandler = (list: Array<any>) => {
      isImmediate.value = false;
      let ids = list.map(item => item?.id) || [];
      ids = ids.filter(item => item);
      emit("update:modelValue", ids);
    };
    const init = async () => {
      if (props.modelValue?.length) {
        loading.value = true;
        const params = { ids: props.modelValue };
        const res = await queryFileList(params, () => {
          loading.value = false;
        });
        loading.value = false;
        if (!res?.length) return;
        fileList.value = res;
      }
    };
    const water = watch(
      () => props.modelValue,
      () => {
        if (isImmediate.value) {
          init();
        } else {
          water();
        }
      },
      {
        immediate: true,
        deep: true
      }
    );
    return () => (
      <FileUpload
        v-loading={loading.value}
        fileType={fileType.value}
        fileList={fileList.value}
        fileData={{ moduleName: props.moduleName }}
        countLimit={props.limit}
        fileAccept={props.fileAccept}
        {...attrs}
        onChangeFileList={changeFileListHandler}
      />
    );
  }
});
